package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


// 登陆控制
// 适配器模式
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        UserInfo user = null;

        // 1: 获取当前请求方法对象
        // 拦截器可以拦截所有请求, 包括动态 跟静态, 动态请求方法对象(HandlerMethod)
        // 而静态请求对象不是HandlerMethod对象
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            String userToken = CookieUtil.getUserToken(request, response);
            user = userInfoRedisService.getUserByToken(userToken);
            // 2: 判断该请求头上是否贴有@RequireLogin
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                // 3: 如果贴了, 需要进行登陆校验
                if(user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        // 4: 如果没贴, 直接放行
        // 让所有请求, 都可以共享用户对象
        request.getSession().setAttribute("userInfo", user);

        return true;
    }
}
